package demo1;

import java.sql.*;

public class GoodsDAOImpl {

    public Goods buyGoods(Long id,Long count) {
        Goods goods = null;
        try(Connection connection = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/myfirst?serverTimezone=UTC",
                "root","123456")) {
            //启动事务
            connection.setAutoCommit(false);
            //使用数据库悲观锁 for update
            PreparedStatement ps = connection.prepareStatement("select * from tb_goods where goods_id=? for update ");
            ps.setLong(1,id);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                goods = new Goods();
                goods.setGoodsId(rs.getLong("goods_id"));
                goods.setGoodsName(rs.getString("goods_name"));
                goods.setGoodsStock(rs.getLong("goods_stock"));
            }
            if(goods.getGoodsStock() >= count){
                goods.setGoodsStock(goods.getGoodsStock() - count);
                ps = connection.prepareStatement("update tb_goods set goods_stock = goods_stock-? where goods_id=?");
                ps.setLong(1,count);
                ps.setLong(2,id);
                ps.executeUpdate();
                System.out.println(Thread.currentThread().getName()+"购买成功！"+goods);
            }else{
                System.out.println(Thread.currentThread().getName()+"库存不足！"+goods);
            }
            //提交事务，释放锁
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return goods;
    }

    public static void main(String[] args) {
        GoodsDAOImpl goodsDAO = new GoodsDAOImpl();
        for(int i = 0;i < 10;i++) {
            new Thread(() -> {
                goodsDAO.buyGoods(1L,2L);
            }).start();
        }
    }
}
